//
//  EventsCalendarViewController.m
//  KG
//
//  Created by Eugene Braginets on 14.03.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "EventsCalendarViewController.h"
#import "bannerView.h"
#import "AppDelegate.h"
#import "EventItem.h"
#import "eventCellViewController.h"
#import "EventInfoViewController.h"

@implementation EventsCalendarViewController
@synthesize tableView = _tableView;
@synthesize bannerViewController=_bannerViewController;
@synthesize eventCell=_eventCell;
@synthesize activityIndicator = _activityIndicator;
@synthesize error = _error;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.navigationItem.title=@"Events Calendar";
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector: @selector(loadData:)
                                                     name:kEventItem object: nil];
    }
    return self;
    
}


#pragma mark - View lifecycle
- (void)viewDidLoad
{
    
//    for (EventItem* item in kEventsArray){
//        NSOperationQueue *queue = [NSOperationQueue new];
//        NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
//                                            initWithTarget:self
//                                            selector:@selector(loadImage:) 
//                                            object:item];
//        [queue addOperation:operation]; 
//    }
     
    bannerView *bannerVC=[[bannerView alloc] init];
    [self.view addSubview:bannerVC.view];
    [bannerVC animate];
    self.bannerViewController=bannerVC;
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:kEventItem];
    [self setTableView:nil];
    [self setActivityIndicator:nil];
    [self setError:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void) viewWillAppear:(BOOL)animated {
    
    [myAppDelegate getData:kGetEventURL
                   andType:kEventItem];
    
    [self.error setHidden:YES];
    [self.activityIndicator setHidden:NO];
    [self.tableView setHidden:YES];
    self.navigationItem.title=@"Events Calendar";
}

#pragma mark - TableView  delegate

// Customize the number of sections in the table view.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellText = @"Go get some text for your cell.";
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:20.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    
    return labelSize.height + 60;    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [kEventsArray count];
}



// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *MyIdentifier = @"MyIdentifier";
    MyIdentifier = @"tblCellView";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier];
            cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];
        }
        
    EventItem* object=[kEventsArray objectAtIndex:indexPath.row];
    
    
	cell.textLabel.text=[object name];
    cell.detailTextLabel.text=[object startdate];

    [cell.detailTextLabel setTextColor:[UIColor whiteColor]];
//    int sec=[[NSDate date] timeIntervalSince1970];
//    if ([object.startdatetimestamp intValue]<sec) {
//        [cell.eventImage setAlpha:0.6];
//        [cell.nameEvent setAlpha:0.6];
//        [cell.startDate setAlpha:0.6];
//    }
//    else
//        [cell.nameEvent setTextColor:[UIColor blackColor]];
    
//    
//    UIImage* cellImage=[[kEventsArray objectAtIndex:indexPath.row] image];
    
//    float width=cellImage.size.width;
//    float height=cellImage.size.height;
//    float ratio=width/height;

    
//    UIImageView *imageView = [ [ UIImageView alloc ] initWithFrame:CGRectMake(0.0, 0.0, 65, 65)];
//    imageView.image = cellImage;
//    imageView.contentMode=UIViewContentModeScaleAspectFill;
//    
//    
//    
//    [cell.eventImage addSubview:imageView];
//    [cell.eventImage setImage:cellImage];
//    [cell.eventImage setContentMode:UIViewContentModeTop];
//    [cell.eventImage setContentMode:UIViewContentModeTop];
    //    cell.playerImage=[myAppDelegate roundCorners:cell.playerImage frameSize:CGSizeMake(50,50) radius:9.0 frameBorderThickness:0];
//    //  

    
    UIView *bgColorView = [[UIView alloc] init];
    [bgColorView setBackgroundColor:[UIColor colorWithRed:.25 green:.3 blue:.05 alpha:0.7]];
    [cell setSelectedBackgroundView:bgColorView];
    [cell setAccessoryView:[self makeDetailDisclosureButton]];
    
//    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    
//    [cell.nameEvent setHighlightedTextColor:[UIColor whiteColor]];
//    [cell.startDate setHighlightedTextColor:[UIColor whiteColor]];
//    [cell.venue setHighlightedTextColor:[UIColor whiteColor]];
    
    //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    
    return cell;
}




- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	// the user clicked one of the OK/Cancel buttons
	if (buttonIndex == [actionSheet destructiveButtonIndex])
	{
        EventItem* eventToStore=[kEventsArray objectAtIndex:[self.tableView indexPathForSelectedRow].row];

        //----- CLICKED OK -----
        EKEventStore *eventStore = [[EKEventStore alloc] init];
        
        EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
        event.title     = eventToStore.name;
        
        event.startDate = [[NSDate alloc] initWithTimeIntervalSince1970:[eventToStore.startdatetimestamp intValue]];
        event.endDate   = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];
        event.notes=@"Added by KerryGaa iPhone Application";
        
        [event setCalendar:[eventStore defaultCalendarForNewEvents]];
        NSError *err;
        [eventStore saveEvent:event span:EKSpanThisEvent error:&err];   
        NSLog (@"event is added!");
    }
	else if (buttonIndex == [actionSheet cancelButtonIndex])
	{
		NSLog(@"CANCEL!");
        //----- CLICKED CANCEL -----
        
	}
}
- (void) addToiCal {
    
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Add this event to your Calendar?"
                                                             delegate:self
                                                    cancelButtonTitle:@"Cancel"
                                               destructiveButtonTitle:@"OK"
                                                    otherButtonTitles:nil];
	[actionSheet showInView:self.view];
    
    
    //    EventToiCalViewController* viewController=[[EventToiCalViewController alloc] init ];
    //    [self.navigationController pushViewController:viewController animated:YES];
}





- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setBackgroundColor:[UIColor clearColor]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog (@"selected row %d", indexPath.row);
    [self addToiCal];
//    EventInfoViewController* viewController=[[EventInfoViewController alloc] initWithEvent:[kEventsArray objectAtIndex:indexPath.row]];
//    
//    self.navigationItem.title=@"Back";
//    
//    [self.navigationController pushViewController:viewController animated:YES];    
}






- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    NSLog (@"selected accessory from row %d", indexPath.row);
    
    [self addToiCal];
//    EventInfoViewController* viewController=[[EventInfoViewController alloc] initWithEvent:[kEventsArray objectAtIndex:indexPath.row]];
//    
//    self.navigationItem.title=@"Back";
//    
//    [self.navigationController pushViewController:viewController animated:YES];  
    
}

#pragma mark - custom methods

- (void) updateUI {

    [self.error setHidden:YES];
    [self.tableView setHidden:NO];
    [self.tableView reloadData];
    [self.activityIndicator setHidden:YES];
}

- (void) showError{
    [self.error setHidden:NO];
    [self.activityIndicator setHidden:YES];
}
- (void) loadData:(NSNotification*) object {
    

    if ([kEventsArray objectAtIndex:0]) {
        if ([[[kEventsArray objectAtIndex:0] description] isEqualToString:@"nodata"]) {
            [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
        }
        else {
            [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
        }
    }


}

- (void)loadImage:(EventItem *)item {
    
    //    int ind=[index intValue];
    
    if (item.image) {
        NSLog (@"image is already loaded for itemId: %@",item.itemid);
        return;   
    }
    else {
        NSLog (@"loading image for itemId: %@",item.itemid);
    }
    
    NSString *imageAddr=[NSString stringWithString:item.imageAddr];
    
    NSLog (@"ImageUrl: %@", imageAddr);
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageAddr]];
    UIImage* image = [[UIImage alloc] initWithData:imageData];
    
    [item setImage:image];
    //    float width=image.size.width;
    //    float height=image.size.height;
    //    float ratio=width/height;
    //
    //    
    //    [item setImage:[myAppDelegate scale:image toSize:CGSizeMake(150*ratio, 150)]];
    //        
    [self performSelectorOnMainThread:@selector(imageDidLoad:) withObject:item waitUntilDone:NO];
}

- (void) imageDidLoad:(DataItem *)item {
    NSLog (@"image for itemId:%@ is loaded!",item.itemid);
    [self.tableView reloadData];
}


- (UIButton *) makeDetailDisclosureButton {
    UIButton * button =[UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"icalbtn"] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor clearColor]];
    [button setFrame:CGRectMake(0, 0, 40, 40)];
    
    [button setImage:[UIImage imageNamed:@"icalbtn_hl"] forState:UIControlStateHighlighted];
    [button setImage:[UIImage imageNamed:@"icalbtn_hl"] forState:UIControlStateSelected];
    
    
    [button addTarget: self
               action: @selector(accessoryButtonTapped:withEvent:)
     forControlEvents: UIControlEventTouchUpInside];
    
    return ( button );
}



//helper for accessoryButtonTapped
- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
    if ( indexPath == nil )
        return;
    [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
    
}

#pragma mark - other ViewController methods

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    NSLog(@"Events Calendar Memory Warning");
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

@end
